/**
 * Created with JetBrains PhpStorm.
 * User: Dinh Hoa
 * Date: 5/7/13
 * Time: 10:36 PM
 * To change this template use File | Settings | File Templates.
 */
var id = null;

$(document).ready(function () {
    $('#main-menu a').each(function (index) {
        if (this.href.trim() == window.location)
            $(this).addClass("selected-main-menu");
    });

    // reading account list from database
    if (document.getElementById('account_list') != null) {
        $("#account_list").ready(function () {
            $("#account_list").css("display", "block");
            readAccount("");
        });
    }

    // reading category list from database
    if (document.getElementById('category_list') != null) {
        $("#category_list").ready(function () {
            $("#category_list").css("display", "block");
            readCategory("");
        });
    }

    // reading news list from database
    if (document.getElementById('news_list') != null) {
        $("#news_list").ready(function () {
            $("#news_list").css("display", "block");
            readNews("");
        });
    }

    // reading product list from database
    if (document.getElementById('product_list') != null) {
        $("#product_list").ready(function () {
            $("#product_list").css("display", "block");
            $("#ime_product").val(generateIMEProduct());
            readProducts("");
        });
    }
});

// CATERGORY MANAGEMENT
function resetCategory() {
    $("#id_cat").val('');
    $("#cat_name").focus();
}

function showEditFormCategory(index, cat_name) {
    $("#id_cat").val(index);
    $("#cat_name").val(urldecode(cat_name));
    $("#cat_name").focus();
    return false;
}

function readCategory(datastr) {
    $.ajax({
        type: "POST",
        url: "getListCategory.php",
        data: datastr,
        cache: false,
        success: function (html) {
            $("#category_list").html(html);
        }
    });

    return false;
}

function deleteCategory() {
    if (id != null) {
        var datastr = "id_cat=" + id;

        $.ajax({
            type: "POST",
            url: "deleteCategory.php",
            data: datastr,
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },
            success: function (html) {
                if (html.trim() === 'fail') {
                    alert("Danh mục đang được sử dụng, không thể xóa!");
                } else {
                    if ($("#id_cat").val() == id) {
                        $("#id_cat").val('');
                    }
                    readCategory("");
                }
            }
        });

        $("#dialog").dialog("close");

        return false;
    }

    return false;
}

function createNewCategory() {
    var id_cat = $("#id_cat").val();
    var cat_name = encodeURIComponent($("#cat_name").val());

    if (id_cat.trim() == '') {
        id_cat = null;
    }

    if (cat_name.trim() != '') {
        var datastr = 'id_cat=' + id_cat + '&cat_name=' + cat_name;
        $.ajax({
            type: "POST",
            url: "createNewCategory.php",
            data: datastr,
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },
            success: function (html) {
                readCategory("");
                $("#message").css("display", "block");
                $("#message").fadeIn("slow");
                $("#message").html(html);
                $("#message").fadeOut(2000);
                $("#id_cat").val('');
                $("#cat_name").val('');
            }
        });
    }

    return false;
}

/// NEWS MANAGEMENT
function readNews(datastr) {
    $.ajax({
        type: "POST",
        url: "getListNews.php",
        data: datastr,
        cache: false,
        success: function (html) {
            $("#news_list").html(html);
        }
    });

    return false;
}

function showEditFormNews(index, title, url_image, short_desc, description) {
    $("#id_news").val(index);
    $("#name").val(urldecode(title));
    $("#short_desc").val(urldecode(short_desc));
    CKEDITOR.instances['description'].setData(urldecode(description));
    $("#image_url").val(url_image);
    //$("#sample_image").html('<img src="' + url_image + '">');
    $("#name").focus();

    return false;
}

function deleteNews() {
    if (id != null) {
        var datastr = "id_news=" + id;

        $.ajax({
            type: "POST",
            url: "deleteNews.php",
            data: datastr,
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },

            success: function (html) {
                readNews("");
                if ($("#id_news").val() == id) {
                    $("#id_news").val('');
                }
            }
        });

        $("#dialog").dialog("close");

        return false;
    }

    return false;
}

function createNews() {
    var id_news = $("#id_news").val();
    var name = encodeURIComponent($("#name").val());
    var short_desc = encodeURIComponent($("#short_desc").val());
    var description = encodeURIComponent(CKEDITOR.instances['description'].getData());
    var image_url = ($("#image_url").val());


    if (id_news.trim() == '') {
        id_news = null;
    }

    if (name.trim() != '' && description.trim() != '') {
        var datastr = 'id_news=' + id_news + '&name=' + name + '&short_desc=' + short_desc + '&image_url=' + image_url + '&description=' + description;
        $.ajax({
            type: "POST",
            url: "createNews.php",
            data: datastr,
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },

            success: function (html) {
                readNews("");
                $("#message").css("display", "block");
                $("#message").fadeIn("slow");
                $("#message").html(html);
                $("#message").fadeOut(2000);
                $("#newsForm")[0].reset();

                $("#id_news").val('');
                CKEDITOR.instances['description'].setData('');
                $("#image_url").val('../images/default.jpg');
                //$("#sample_image").html('<img src="../images/default.jpg">');
            }
        });
    }

    return false;
}

function resetFormNews() {
    $("#name").focus();
    $("#id_news").val('');
    CKEDITOR.instances['description'].setData('');
    $("#sample_image").html('<img src="../images/default.jpg">');
}
// END NEWS

//// product
function resetFormProduct() {
    $("#id_product").val(null);
    $("#name_product").val(null);
    $("#price_product").val(0);
    $("#ime_product").val(generateIMEProduct());
    $("#brief_product").val('');
    CKEDITOR.instances['content_product'].setData('');
    $("#image_url").val('../images/default.jpg');
    $("#sample_image").html('<img src="../images/default.jpg">');
    $("#name_product").focus();
}

function generateIMEProduct() {
    return "MT-" + (Math.floor(Math.random() * 900000) + 100000);
}

function readProducts(datastr) {
    $.ajax({
        type: "POST",
        url: "getListProducts.php",
        data: datastr,
        cache: false,
        success: function (html) {
            $("#product_list").html(html);
        }
    });

    return false;
}

function showEditFormProduct(index, name, ime, price, cat_id, short_desc, description, url_image, fac) {
    $("#id_product").val(index);
    $("#name_product").val(urldecode(name));
    $("#price_product").val(price);
    $("#ime_product").val(ime);
    $("#brief_product").val(urldecode(short_desc));
    $("#cat_product").val(cat_id);
    CKEDITOR.instances['content_product'].setData(urldecode(description));
    $("#image_url").val(url_image);
    $("#manufactory").val(urldecode(fac));
    //$("#sample_image").html('<img src="' + url_image + '">');
    $("#name_product").focus();

    return false;
}

function deleteProduct() {
    if (id != null) {
        var datastr = "id_product=" + id;

        $.ajax({
            type: "POST",
            url: "deleteProduct.php",
            data: datastr,
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },

            success: function (html) {
                if ($("#id_product").val() == id) {
                    $("#id_product").val('');
                }
                readProducts("");
            }
        });

        $("#dialog").dialog("close");

        return false;
    }

    return false;
}

function createProduct() {
    var id_product = $("#id_product").val();
    var name_product = encodeURIComponent($("#name_product").val());
    var price_product = $("#price_product").val();
    var ime_product = $("#ime_product").val();
    var cat_product = $("#cat_product").val();
    var brief_product = encodeURIComponent($("#brief_product").val());
    var content = encodeURIComponent(CKEDITOR.instances['content_product'].getData());
    var url_image = ($("#image_url").val());
    var fac = encodeURIComponent($("#manufactory").val());

    if (id_product.trim() == '') {
        id_product = null;
    }

    if (name_product.trim() != '' && price_product.trim() != '' && isNumber(price_product)) {
        var datastr = 'fac=' + fac + '&id_product=' + id_product + '&name_product=' + name_product + '&content=' + content + '&url_image=' + url_image
            + '&ime_product=' + ime_product + '&cat_product=' + cat_product + '&brief_product=' + brief_product + '&price_product=' + price_product;

        $.ajax({
            type: "POST",
            url: "createProduct.php",
            data: datastr,
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },

            success: function (html) {
                readProducts("");
                $("#message").css("display", "block");
                $("#message").fadeIn("slow");
                $("#message").html(html);
                $("#message").fadeOut(2000);

                $("#id_product").val('');
                $("#name_product").val('');
                $("#price_product").val('');
                $("#ime_product").val(generateIMEProduct());
                $("#brief_product").val('');
                $("#manufactory").val('');
                CKEDITOR.instances['content_product'].setData('');
                $("#image_url").val('../images/default.jpg');
                //$("#sample_image").html('<img src="../images/default.jpg">');
                $("#name_product").focus();
            }
        });
    }

    return false;
}

//END
// ACCOUNT Management
function readAccount(datastr) {
    $.ajax({
        type: "POST",
        url: "getListAccount.php",
        data: datastr,
        cache: false,
        success: function (html) {
            $("#account_list").html(html);
        }
    });

    return false;
}

function showEditFormAccount(index, username, password) {
    $("#id_acc").val(index);
    $("#username").val(username);
    $("#password").val(password);
    $("#username").focus();
    return false;
}

function deleteAccount() {
    if (id != null) {
        var datastr = "id_acc=" + id;

        $.ajax({
            type: "POST",
            url: "deleteAccount.php",
            data: datastr,
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },
            success: function (html) {
                if (html.trim() === 'fail') {
                    alert("không thể xóa!");
                } else {
                    if ($("#id_acc").val() == id) {
                        $("#id_acc").val('');
                    }
                    readAccount("");
                }
            }
        });

        $("#dialog").dialog("close");

        return false;
    }

    return false;
}

function createAccount() {
    var id_acc = $("#id_acc").val();
    var username = $("#username").val();
    var password = $("#password").val();

    if (id_acc.trim() == '') {
        id_acc = null;
    }

    if (username.trim() != '' && password.trim() != '') {
        var datastr = 'id_acc=' + id_acc + '&username=' + username + '&password=' + password;
        $.ajax({
            type: "POST",
            url: "createAccount.php",
            data: datastr,
            cache: false,
            beforeSend: function () {
                $.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#fff'
                } });
            },
            complete: function () {
                $.unblockUI();
            },
            success: function (html) {
                readAccount("");
                $("#message").css("display", "block");
                $("#message").fadeIn("slow");
                $("#message").html(html);
                $("#message").fadeOut(2000);
                $("#accountForm")[0].reset();

                $("#id_acc").val(null);
                $("#username").focus();
            }
        });
    }

    return false;
}

function resetFormAcc() {
    $("#username").focus();
    $("#id_acc").val(null);
}
///END ACOUNT

///// function for validate and other purpose
function showConfirmDialog(index) {
    id = index;
    $("#dialog").dialog();
    return false;
}

function closeDialog() {
    $("#dialog").dialog("close");
    return false;
}

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

///
function gotoPage(url) {
    window.location.href = url;
}
//
function validate(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

// decode
function urldecode(url) {
    return decodeURIComponent(url.replace(/\+/g, ' '));
}

function browserImage() {
    var url_image = window.showModalDialog("dialogImage.php", "", "dialogWidth:700px;dialogHeight:500px;");
    if (url_image != null) {
        $("#image_url").val(url_image.link);
        $("#sample_image").html('<img src="' + url_image.link + '">');
    }
}